package cn.piaoyi.service.imp;

import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.*;

import cn.piaoyi.bean.Category;
import cn.piaoyi.bean.Daily;
import cn.piaoyi.bean.Goods;
import cn.piaoyi.bean.Price;
import cn.piaoyi.dao.CategoryDAO;
import cn.piaoyi.dao.DailyDAO;
import cn.piaoyi.dao.GoodsDAO;
import cn.piaoyi.dao.PriceDAO;
import cn.piaoyi.exception.PiaoyiException;
import cn.piaoyi.service.GoodsService;
import cn.piaoyi.service.web.PageList;
import cn.piaoyi.service.web.Pages;


public class GoodsServiceImp implements GoodsService {

	private static final Log logger = LogFactory.getLog(GoodsServiceImp.class);
	
	private GoodsDAO goodsDAO;
	private DailyDAO dailyDAO;
	private PriceDAO priceDAO;
;	private CategoryDAO categoryDAO;

	public GoodsDAO getGoodsDAO() {
		return goodsDAO;
	}

	public void setGoodsDAO(GoodsDAO goodsDAO) {
		this.goodsDAO = goodsDAO;
	}
	
	public DailyDAO getDailyDAO() {
		return dailyDAO;
	}

	public void setDailyDAO(DailyDAO dailyDAO) {
		this.dailyDAO = dailyDAO;
	}

	public PriceDAO getPriceDAO() {
		return priceDAO;
	}

	public void setPriceDAO(PriceDAO priceDAO) {
		this.priceDAO = priceDAO;
	}

	public CategoryDAO getCategoryDAO() {
		return categoryDAO;
	}

	public void setCategoryDAO(CategoryDAO categoryDAO) {
		this.categoryDAO = categoryDAO;
	}

	/**
	 * 保存Goods对象
	 * 
	 * @param goods
	 * 			Goods对象
	 * @return Goods
	 * 			Goods对象
	 */
	public Goods createGoods(Goods goods) throws PiaoyiException{
		try {
			goods = this.getGoodsDAO().saveGoods(goods);
			return goods;
		} catch (Exception e) {
			logger.error(e);
			throw new PiaoyiException(e);
		}
	}

	
	/**
	 * 保存Goods对象
	 * 
	 * @param goods
	 * 			Goods对象
	 * @return Goods
	 * 			Goods对象
	 */
	public Goods updateGoods(Goods goods) throws PiaoyiException{
		try {
			goods = this.getGoodsDAO().updateGoods(goods);
			return goods;
		} catch (Exception e) {
			logger.error(e);
			throw new PiaoyiException(e);
		}
	}
	
	/**
	 * 根据主键ID获取Goods对象
	 * 
	 * @param id
	 * 			主键ID
	 * @return Goods
	 * 			Goods对象
	 */
	public Goods findGoodsById(long id){
		return this.getGoodsDAO().findGoodsById(id);
	}
	
	/**
	 * 获取Goods列表
	 * 
	 * @param categoryId
	 * 			long
	 * @param orderby
	 *            String
	 * @param ascOrDesc
	 *            int
	 * @param pages
	 * 			  Pages
	 * @return PageList
	 * 			Goods对象列表
	 */
	public PageList findGoodses(int cityId,String categoryCode,String name,int isShow,int state,String orderby, int ascOrDesc,Pages pages){
		long categoryId = -1;
		//有频道
		if(StringUtils.isNotBlank(categoryCode)){
			Category c = this.getCategoryDAO().findCategoryByCode(categoryCode);
			if(c!=null){
				categoryId = c.getId();
			}
		}
		PageList pl = new PageList();
        if (pages.getTotalNum() == -1) {
            pages.setTotalNum(this.getGoodsDAO().getGoodsNum(cityId,categoryId,name,isShow,state));
        }
        pages.executeCount();
        if(pages.getTotalNum() == 0){
        	pl.setObjectList(null);
        	pl.setPages(pages);
        	return pl;
        }
		List l = this.getGoodsDAO().findGoodses(cityId,categoryId,name,isShow,state,orderby, ascOrDesc,pages.getSpage(), pages.getPerPageNum());
		if(l == null || l.isEmpty()){
	   		 pl.setObjectList(null);
	   	     pl.setPages(pages);
	   		 return pl;
		}else{
			for(int i=0;i<l.size();i++){
				Goods g = (Goods) l.get(i);
				List prices = this.getPriceDAO().findPrices(g.getId(), -1, "price", 0,0,1);
				if(prices == null || prices.isEmpty()){
					g.setPrice(0);
				}else{
					Price p = (Price) prices.get(0);
					g.setPrice(p.getPrice());
				}
				List dl = this.getDailyDAO().findDailys(g.getId(), "startTime", 0, 0, 1);
				if(dl == null || dl.isEmpty()){
					g.setPrices("");
				}else{
					Daily d = (Daily) dl.get(0);
					List pids = this.getPriceDAO().findPricePrices(g.getId(), d.getId(), "price", 0);
					g.setPrices(list2String(pids));
					logger.info(list2String(pids));
				}
			}
			
			pl.setObjectList(l);
	        pl.setPages(pages);
	        return pl;
		}
	}
	
	public PageList findGoodses(int cityId,String categoryCode,String name,int isShow,int state,int time,String startTime,String endTime,int startPrice,int endPrice,String orderby, int ascOrDesc,Pages pages){
		PageList pl = new PageList();
		long categoryId = -1;
		//有频道
		if(StringUtils.isNotBlank(categoryCode)){
			Category c = this.getCategoryDAO().findCategoryByCode(categoryCode);
			if(c!=null){
				categoryId = c.getId();
			}
		}
		List ids = new ArrayList();
		if(startPrice !=-1 || endPrice != -1){
			ids = this.getPriceDAO().findPriceGoodsIds(startPrice, endPrice);
			if(ids == null || ids.isEmpty()){
				pages.setTotalNum(0);
				pl.setObjectList(null);
	        	pl.setPages(pages);
	        	return pl;
			}
		}

        if (pages.getTotalNum() == -1) {
            pages.setTotalNum(this.getGoodsDAO().getGoodsNum(cityId,categoryId, ids, name, isShow, state, time, startTime, endTime));
        }
        pages.executeCount();
        if(pages.getTotalNum() == 0){
        	pl.setObjectList(null);
        	pl.setPages(pages);
        	return pl;
        }
		List l = this.getGoodsDAO().findGoodses(cityId,categoryId, ids, name, isShow, state, time, startTime, endTime,orderby, ascOrDesc,pages.getSpage(), pages.getPerPageNum());
		if(l == null || l.isEmpty()){
	   		 pl.setObjectList(null);
	   	     pl.setPages(pages);
	   		 return pl;
		}else{
			for(int i=0;i<l.size();i++){
				Goods g = (Goods) l.get(i);
				List prices = this.getPriceDAO().findPrices(g.getId(), -1, "price", 0,0,1);
				if(prices == null || prices.isEmpty()){
					g.setPrice(0);
				}else{
					Price p = (Price) prices.get(0);
					g.setPrice(p.getPrice());
				}
				List dl = this.getDailyDAO().findDailys(g.getId(), "startTime", 0, 0, 1);
				if(dl == null || dl.isEmpty()){
					g.setPrices("");
				}else{
					Daily d = (Daily) dl.get(0);
					List pids = this.getPriceDAO().findPricePrices(g.getId(), d.getId(), "price", 0);
					g.setPrices(list2String(pids));
					//logger.info(list2String(pids));
				}
			}
			
			pl.setObjectList(l);
	        pl.setPages(pages);
	        return pl;
		}
	}
	
	/**
	 * 获取Goods列表
	 * 
	 * @param categoryCode
	 * 			String
	 * @param name
	 * 			String
	 * @param isShow
	 * 			int
	 * @param state
	 * 			int
	 * @param orderby
	 *            String
	 * @param ascOrDesc
	 *            int
	 * @param firstResult
	 *            int
	 * @param maxResults
	 *            int
	 * @return List
	 * 			Goods对象列表
	 */
	public List findGoodses(int cityId,String categoryCode,String name,int isShow,int state,String orderby, int ascOrDesc, int firstResult, int maxResults){
		long categoryId = -1;
		//有频道
		if(StringUtils.isNotBlank(categoryCode)){
			Category c = this.getCategoryDAO().findCategoryByCode(categoryCode);
			if(c!=null){
				categoryId = c.getId();
			}
		}
		List l = this.getGoodsDAO().findGoodses(cityId,categoryId,name,isShow,state,orderby, ascOrDesc,firstResult, maxResults);
		if(l == null || l.isEmpty()){
	   		return null;
		}else{
			for(int i=0;i<l.size();i++){
				Goods g = (Goods) l.get(i);
				List prices = this.getPriceDAO().findPrices(g.getId(), -1, "price", 0,0,1);
				if(prices == null || prices.isEmpty()){
					g.setPrice(0);
				}else{
					Price p = (Price) prices.get(0);
					g.setPrice(p.getPrice());
				}
				List dl = this.getDailyDAO().findDailys(g.getId(), "startTime", 0, 0, 1);
				if(dl == null || dl.isEmpty()){
					g.setPrices("");
				}else{
					Daily d = (Daily) dl.get(0);
					List pids = this.getPriceDAO().findPricePrices(g.getId(), d.getId(), "price", 0);
					g.setPrices(list2String(pids));
				}
			}
			return l;
		}
	}
	
	/**
	 * 删除Goods对象
	 */
	public void removeGoodsById(long id){
		this.getGoodsDAO().removeGoodsById(id);
	}
	
	private  String list2String(List set) {
		StringBuffer sb = new StringBuffer();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			sb.append(it.next());
			sb.append(",");
		}
		String fs = sb.toString();
		if (fs != null && fs.length() > 0 && fs.endsWith(",")) {
			fs = fs.substring(0, fs.length() - 1);
		}
		return fs;
	}
}
